package net.hvacapp.cmvrfforandroid.ui.mine;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.mirror.android.common.util.StringUtils;

import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.ui.BaseActivity;
import net.hvacapp.cmvrfforandroid.ui.mine.model.GetNoticeDataResp;
import net.hvacapp.cmvrfforandroid.ui.mine.model.GetPublishDataResp;
import net.hvacapp.cmvrfforandroid.widget.IOSAlertView;
import net.hvacapp.cmvrfforandroid.widget.UserSelectionView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@EActivity(R.layout.activity_publish)
public class PublishActivity extends BaseActivity {

    @ViewById(R.id.cet_title)
    EditText mTitleCet;
    @ViewById(R.id.cet_content)
    EditText mContentCet;

    @ViewById(R.id.sel_picture)
    UserSelectionView mPicSel;
    @ViewById(R.id.iv_image)
    ImageView mImageIv;

    @ViewById(R.id.tv_publish)
    TextView mPublishTv;

    String mFilePath;

    private Dialog mProgressDlg;

    private String mUrl;
    private int mType; //0：公告  1：建议

    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    // 创建一个以当前时间为名称的文件
    File tempFile = new File(Environment.getExternalStorageDirectory(),getPhotoFileName());

    /**
     * 页面加载完后执行
     */
    @AfterViews
    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        initEvent();
    }

    @Override
    public void initBoot() {

    }

    private void initEvent() {
        mPicSel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });

        mPublishTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //提交
                publish();
            }
        });
    }

    @SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled"})
    @Override
    public void initData(Intent intent) {
        mType = intent.getIntExtra("type", 0);
        if (mType == 0) {
            setupToolbar(0, "新建公告", null);
        }
        else {
            setupToolbar(0, "发布意见", null);
        }
        mPicSel.setTitleString("选择图片");
        mPicSel.setInfoString("");

    }

    /**
     * 页面名称
     */
    @Override
    public String getName() {
        return "";
    }

    //提示对话框方法
    private void showDialog() {
        new AlertDialog.Builder(this)
                .setTitle("选择图片")
                .setPositiveButton("拍照", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                        // 调用系统的拍照功能
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        // 指定调用相机拍照后照片的储存路径
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                        startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
                    }
                })
                .setNegativeButton("相册", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                        intent.setType("image/*");
                        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                    }
                }).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub



        switch (requestCode) {
            case PHOTO_REQUEST_TAKEPHOTO:
//                startPhotoZoom(Uri.fromFile(tempFile), 150);
                int width = mImageIv.getWidth();
                int height = mImageIv.getHeight();

                BitmapFactory.Options factoryOptions = new BitmapFactory.Options();

                factoryOptions.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(tempFile.getPath(), factoryOptions);

                int imageWidth = factoryOptions.outWidth;
                int imageHeight = factoryOptions.outHeight;

                // Determine how much to scale down the image
                int scaleFactor = Math.min(imageWidth / width, imageHeight
                        / height);

                // Decode the image file into a Bitmap sized to fill the
                // View
                factoryOptions.inJustDecodeBounds = false;
                factoryOptions.inSampleSize = scaleFactor;

                Bitmap bitmap1 = BitmapFactory.decodeFile(tempFile.getPath(),
                        factoryOptions);
                mFilePath = tempFile.getPath();

                mImageIv.setImageBitmap(bitmap1);



                break;

            case PHOTO_REQUEST_GALLERY:
                if (data != null) {
                    Uri uri = data.getData();
                    ContentResolver cr = this.getContentResolver();
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                        /* 将Bitmap设定到ImageView */
                        mImageIv.setImageBitmap(bitmap);

                        //    这里开始的第二部分，获取图片的路径：

                        mFilePath = getRealPathFromURI(uri);
//                        imgPath.setText(path);


                    } catch (FileNotFoundException e) {

                    }
                }
                break;

            case PHOTO_REQUEST_CUT:
                if (data != null)
                    setPicToView(data);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    private String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if(cursor.moveToFirst()){;
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }


    private void startPhotoZoom(Uri uri, int size) {
        Intent intent = new Intent("com.android camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("return-data", true);

        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    //将进行剪裁后的图片显示到UI界面上
    private void setPicToView(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (bundle != null) {
            Bitmap photo = bundle.getParcelable("data");
            Resources res=getResources();//获取资源
            Drawable drawable = new BitmapDrawable(res, photo);
            mImageIv.setImageDrawable(drawable);
        }
    }

    // 使用系统当前日期加以调整作为照片的名称
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    private void publish() {
        String title = new String(Base64.encode(mTitleCet.getText().toString().getBytes(), Base64.DEFAULT));
        String content = new String(Base64.encode(mContentCet.getText().toString().getBytes(), Base64.DEFAULT));
        if (StringUtils.isEmpty(title)) {
            showMessage("标题不能为空！");
            return;
        }
        else if (StringUtils.isEmpty(content)) {
            showMessage("内容不能为空");
            return;
        }


        String url;
        if (mType == 0) {
            //公告
            url = HttpConstant.HTTP_URL + "2.0/postmanager.svc/?tk=" + AccountManager.getInstance().getToken();
        }
        else {
            url = HttpConstant.HTTP_URL + "2.0/suggestionmanager.svc/?tk=" + AccountManager.getInstance().getToken();
        }

        Map<String, Object> param = new HashMap<>();
        param.put("title", title);
        param.put("content", content);

        BasicHttpClient.httpPostAsync(url, param, new HttpCallbackHandle<GetPublishDataResp>() {
            @Override
            public void onSuccess(GetPublishDataResp obj) {
                // 成功
                if (mType == 0) {
                    //公告
                    uploadImage(obj.getSendPostResult());
                }
                else {
                    uploadImage(obj.getSendSuggestionResult());
                }

            }

            @Override
            public void onFailure(String response) {

                showMessage("提交失败，请重试！");
            }
        });


    }

    private void uploadImage(String guidId) {

        if (StringUtils.isEmpty(mFilePath)){
            IOSAlertView.showAlertView(PublishActivity.this, "提示",
                    "发布成功！", "确定",
                    new IOSAlertView.OnAlertViewClickListener() {

                        @Override
                        public void OnAlertViewClick(int position) {
                            if (position == 0) {
                                Intent intent = new Intent();
                                setResult(RESULT_OK, intent);
                                finish();
                            }
                        }
                    });
            return;
        }
        String url;
        if (mType == 0) {
            //公告
            url = HttpConstant.HTTP_URL + "2.0/postmanager.svc/sendpic?tk=" + AccountManager.getInstance().getToken()
            + "&id=" + guidId;
        }
        else {
            url = HttpConstant.HTTP_URL + "2.0/suggestionmanager.svc/sendpic?tk=" + AccountManager.getInstance().getToken()
                    + "&id=" + guidId;
        }

        File file = new File(mFilePath);
        if (!file.exists()) {
            return;
        }
        List<File> files = new ArrayList<>();
        files.add(file);

        mProgressDlg = createProgressBarDialog(this, "图片上传中...");
        mProgressDlg.show();

        String mimeType = "image/jpeg";
        BasicHttpClient.httpPostFilesAsync(url, files, mimeType, new HttpCallbackHandle<GetPublishDataResp>() {
            @Override
            public void onSuccess(GetPublishDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                IOSAlertView.showAlertView(PublishActivity.this, "提示",
                        "发布成功！", "确定",
                        new IOSAlertView.OnAlertViewClickListener() {

                            @Override
                            public void OnAlertViewClick(int position) {
                                if (position == 0) {
                                    Intent intent = new Intent();
                                    setResult(RESULT_OK, intent);
                                    finish();
                                }
                            }
                        });
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                IOSAlertView.showAlertView(PublishActivity.this, "提示", "发布失败！", "确定", null);
            }
        });
    }


}
